<?php

namespace KukePay\Ali\Payment\Notify;

use KukePay\Ali\Payment\Kernel\ConfigFactory;
use KukePay\Ali\Payment\Kernel\SignFactory;

class Factory
{
    private $config;

    private $sign;

    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
        $this->sign = SignFactory::getInterface();
    }


    /**
     * 验证签名
     * @param $params
     * @return bool
     */
    public function checkSign($params)
    {
        $sign = $params['sign'];
        $params['sign_type'] = null;
        $params['sign'] = null;
        return $this->verify($this->sign->getSignContent($params), $sign);
    }

    /**
     * @param $data
     * @param $sign
     * @return bool
     */
    protected function verify($data, $sign)
    {
        $pubKey = $this->config->getAliPublicKey();

        $signType = $this->config->getSignType();

        $res = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($pubKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        //调用openssl内置方法验签，返回bool值

        $result = FALSE;
        if ("RSA2" == $signType) {
            $result = (openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256) === 1);
        } else {
            $result = (openssl_verify($data, base64_decode($sign), $res) === 1);
        }


        return $result;
    }

}